package dnl.jexem.prcs;

import java.util.List;

import org.apache.commons.lang.SystemUtils;

/**
 * 
 * @author Daniel Orr
 * 
 */
public class ProcessUtils {

	private static ProcessOperations processOperations;
	private static JpsProcessOperations jpsProcessOperations = new JpsProcessOperations();
	static {
		if (SystemUtils.IS_OS_LINUX) {
			processOperations = new UnxCommandsProcessOperations();
		}
		if (SystemUtils.IS_OS_WINDOWS) {
			processOperations = new WindowsCommandsProcessOperations();
		}
	}

	public static void main(String[] args) {

	}

	/**
	 * Gets a list of processes running on this machine that is based on the
	 * output of a command. On NIX systems it executes a 'ps -aef' and on Win it
	 * executes 'tasklist /v'.
	 * 
	 * @return
	 */
	public static List<ProcessInfo> getProcesses() {
		return processOperations.getProcesses();
	}

	/**
	 * "Greps" the processes for the given expression and returns all matching
	 * <code>ProcessInfo</code>s.
	 * 
	 * @param grepExpression
	 * @return
	 */
	public static List<ProcessInfo> grepProcesses(String grepExpression) {
		return processOperations.grepProcesses(grepExpression);
	}

	/**
	 * kills the processes that match the given expression.
	 * 
	 * @param grepExpression
	 * @return
	 */
	public static boolean killProcesses(String grepExpression) {
		List<ProcessInfo> grepProcesses = processOperations.grepProcesses(grepExpression);
		boolean someFailed = false;
		for (ProcessInfo processInfo : grepProcesses) {
			if (!processOperations.killProcess(processInfo.getProcessID())) {
				someFailed = true;
			}
		}
		return someFailed;
	}

	/**
	 * Attempts to kill the process with the given id.
	 * 
	 * @param pid
	 */
	public static void killProcess(int pid) {
		processOperations.killProcess(pid);
	}

	/**
	 * Kills all processes that match the given expression. The expression is
	 * being searched in the <code>mainOrJar</code> and <code>arguments</code>
	 * attributes of existing Java processes. Carefull with the expression
	 * though ...
	 * 
	 * @param grepExpression
	 */
	public static void killJavaProcesses(String grepExpression) {
		List<JavaProcessInfo> javaProcesses = grepJavaProcesses(grepExpression);
		for (JavaProcessInfo javaProcessInfo : javaProcesses) {
			killProcess(javaProcessInfo.getProcessID());
		}
	}

	/**
	 * Uses the given expression to resolve Java processes.
	 * 
	 * @param grepExpression
	 * @return
	 */
	public static List<JavaProcessInfo> grepJavaProcesses(String grepExpression) {
		return jpsProcessOperations.grepJavaProcesses(grepExpression);
	}

	/**
	 * Gets info for Java processes running on this machine. This method parses
	 * the output of the jps command and currently returns
	 * <code>JavaProcessInfo</code> that have only a processID, main/jar
	 * attribute, and arguments.
	 * 
	 * @return
	 */
	public static List<JavaProcessInfo> getJavaProcesses() {
		return jpsProcessOperations.getJavaProcesses();
	}

}
